package com.hnevc.weatherdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.InputStream;
import java.util.List;
public class MainActivity extends AppCompatActivity implements
        View.OnClickListener {
    private TextView tvCity; //城市
    private TextView tvWeather; //天气
    private TextView tvTemp; //温度
    private TextView tvWind; //风力
    private TextView tvPm; //PM2.5
    private ImageView ivIcon; // 图标

    private String temp, weather, name, pm, wind;
    private List<WeatherInfo> mWeatherInfos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 初始化文本控件
        initView();
        try {
            //读取weather1.xml文件
            InputStream is = this.getResources().openRawResource(R.raw.weather1);
            //把每个城市的天气信息集合存到weatherInfos中
            mWeatherInfos = WeatherService.getInfosFromXML(is);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "解析信息失败", Toast.LENGTH_SHORT).show();
        }
        //自定义getMap()方法，显示天气信息到文本控件中，默认显示北京的天气
        getMap(1, R.drawable.sun);
    }
    private void initView() {
        tvCity = (TextView) findViewById(R.id.tv_city);
        tvWeather = (TextView) findViewById(R.id.tv_weather);
        tvTemp = (TextView) findViewById(R.id.tv_temp);
        tvWind = (TextView) findViewById(R.id.tv_wind);
        tvPm = (TextView) findViewById(R.id.tv_pm);
        ivIcon = (ImageView) findViewById(R.id.iv_icon);
        findViewById(R.id.btn_sh).setOnClickListener(this);
        findViewById(R.id.btn_bj).setOnClickListener(this);
        findViewById(R.id.btn_gz).setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {    //按钮的点击事件
        switch (v.getId()) {
            case R.id.btn_sh:
                getMap(0, R.drawable.cloud_sun);
                break;
            case R.id.btn_bj:
                getMap(1, R.drawable.sun);
                break;
            case R.id.btn_gz:
                getMap(2, R.drawable.clouds);
                break;
        }
    }
    //将城市天气信息分条展示到界面上
    private void getMap(int number, int iconNumber) {
        WeatherInfo weatherInfo = mWeatherInfos.get(number);
        temp = weatherInfo.getTemp();
        weather = weatherInfo.getWeather();
        name = weatherInfo.getName();
        pm = weatherInfo.getPm();
        wind = weatherInfo.getWind();
        tvCity.setText(name);
        tvWeather.setText(weather);
        tvTemp.setText("" + temp);
        tvWind.setText("风力  : " + wind);
        tvPm.setText("pm: " + pm);
        ivIcon.setImageResource(iconNumber);
    }
}
